package com.lcf.jwt.service;

import com.lcf.jwt.dto.DeptSmallDTO;
import com.lcf.jwt.dto.JobSmallDTO;
import com.lcf.jwt.dto.UserDTO;
import com.lcf.jwt.entity.JwtUser;
import com.lcf.jwt.exception.BadRequestException;
import com.lcf.jwt.mapper.JwtUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author Zheng Jie
 * @date 2018-11-22
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JwtUserDetailsService {

    @Autowired
    private JwtUserMapper jwtUserMapper;

//    private final JwtPermissionService permissionService;

//    public JwtUserDetailsService(UserService userService, JwtPermissionService permissionService) {
//        this.userService = userService;
//        this.permissionService = permissionService;
//    }

//    @Override
    public JwtUser loadUserByUsername(String username){

        JwtUser user = jwtUserMapper.findUserByName(username);
        if (user == null) {
            throw new BadRequestException("账号不存在");
        } else {
            return user;
        }
    }

    public JwtUser createJwtUser(UserDTO user) {
        return new JwtUser(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                user.getAvatar(),
                user.getEmail(),
                user.getPhone(),
                Optional.ofNullable(user.getDept()).map(DeptSmallDTO::getName).orElse(null),
                Optional.ofNullable(user.getJob()).map(JobSmallDTO::getName).orElse(null),
                //"", //permissionService.mapToGrantedAuthorities(user),
                user.getEnabled(),
                user.getCreateTime(),
                user.getLastPasswordResetTime()
        );
    }
}
